const router = require('koa-router')()
const mongoose = require('mongoose')
const stats = require('../helpers/stats')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.get('/', async (ctx, next) => {
  await Promise.all([
    Image.find().sort({timestamp: -1}),
    stats(),
    Image.find().sort({like:-1}).limit(5),
    Comment.find().sort({timestamp:-1}).limit(5)
  ])
    .then(([images,stats,popular,comments1]) => ctx.render('index', {images,stats,popular,comments1}))
    .catch(err => ctx.throw(500, err))
})

module.exports = router
